<?php

use Yaf\Exception\LoadFailed;
use Yaf\Exception;

/**
 * Class ErrorController
 * @name ErrorController
 * @desc 错误控制器, 在发生未捕获的异常时刻被调用
 * @see http://www.php.net/manual/en/yaf-dispatcher.catchexception.php
 */
class ErrorController extends BaseController
{
    /**
     * 从2.1开始, errorAction支持直接通过参数获取异常
     * @param Exception $exception
     * @return bool
     */
    public function errorAction($exception)
    {
        //1. assign to view engine
        //$this->getView()->assign("exception", $exception);

        //5. render by Yaf
        try {
            throw $exception;
        } catch (BadRequestException $ex) {
            // 业务异常
            $code = $ex->getCode();
            $msg = $ex->getMessage();
        } catch (LoadFailed $ex) {
            // 加载失败
            http_response_code(404);
            $code = $ex->getCode();
            $msg = 'LoadFailed';
        } catch (Exception $ex) {
            // 其他异常
            http_response_code(500);
            $code = $ex->getCode();
            $msg = $ex->getMessage();
        }

        return $this->json([], $code, $msg);
    }
}
